<?php
/**
 * Created by Sublime.
 * Author: lingyun
 * Date: 2017-12-07 15:29:32
 * @desc 微信支付配置
 */
namespace app\home\controller;
use think\Controller;
use think\Db;
use alipay\Query;
use alipay\Notify as Alinotify;
class Notify extends Controller{

    //微信回调
    public function notifyweixinpay(){
        $pay = & load_wechat('Pay');
        // 获取支付通知
        $notifyInfo = $pay->getNotify();
        //file_put_contents("1.json", $notifyInfo);
        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            // 接口失败的处理
            //echo $pay->errMsg;
            $json = json_encode($notifyInfo);


        }else{
            $json =json_encode($notifyInfo);

            //支付通知数据获取成功
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                file_put_contents("1.json", $json);
                $noty = Db::table("ys_order")->where("order_sn",$json["out_trade_no"])->find();
                $data = ["order_status"     =>1,
                         "pay_type"         =>2,
                         "pay_status"       =>1,
                         "pay_name"         =>"微信支付",
                         "pay_time"         =>time(),
                         "final_amount"     =>$notifyInfo["cash_fee"]/100,
                         "transaction_id"   =>$notifyInfo["transaction_id"],
                         "pay_code"         =>$notifyInfo["transaction_id"]
                ];
                Db::table("ys_order")->where("order_sn",$notifyInfo["out_trade_no"])->update($data);
                Db::table("ys_notify")	->insert($notifyInfo);
                // $user = Db::table("ys_user")->where("uid",$noty['uid'])->find();
                // $user_wallet_log = [
                //  			"uid"			=>$noty['uid']  ,
                //  			"admin_id"		=> '' ,							//管理员ID，后台变更填写，前台变更不填写
                //  			"store_id"		=> $noty["store_id"] ,			//门店id
                //  			"order_id"		=> $noty["orderid"] ,   		//订单id
                //  			"order_sn"		=> $noty["order_sn"] ,			//订单编号
                //  			"uname"			=> $user["realname"],
                //  			"amount"		=> $notifyInfo["cash_fee"]/100 , 	//变更值
                //  			"cur_amount"	=> $user["user_money"] ,
                //  			"sign"			=>  2,
                //  			"chargetype"	=> 1 , 							//1消费，2充值
                //  			"charge_cn"		=>"微信支付"  , 				 //备注
                //  			"addtime"		=>time()
                //  			];
                // 			Db::table("ys_user_wallet_log")->insertGetId($user_wallet_log);
                // echo $pay->errMsg;
                // $json = json_encode($notifyInfo);
                // file_put_contents("1.json", $json);
                // 支付状态完全成功，可以更新订单的支付状态了
                // 返回XML状态，至于XML数据可以自己生成，成功状态是必需要返回的。
                // <xml>
                //    return_code><![CDATA[SUCCESS]]></return_code>
                //    return_msg><![CDATA[OK]]></return_msg>
                // </xml>
                return xml(['return_code' => 'SUCCESS', 'return_msg' => 'DEAL WITH SUCCESS']);
            }
        }
    }
    /**
     * @Author lignyun
     * @Desc    回调处理会员充值 -- 微信端
     */
    public function wx_notifyrecharge(){
        $pay = & load_wechat('Pay');
        // 获取支付通知
        $notifyInfo = $pay->getNotify();
        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            // 接口失败的处理
            $this->error('支付失败',url('User/index'),1);
        }else{
            //支付通知数据获取成功
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                $order = Db::name('user_wallet_log')->where("order_sn",$notifyInfo['out_trade_no'])->find();
                $member = Db::name('user')->where('uid',$order['uid'])->find();
                $cur_amount = $order['amount']+$member['user_money'];
                $point_rule = Db::name('sys_point')->where('id',3)->find();         //查询积分规则
                $change_point = ceil($order['amount']/$point_rule['score']);        //变更的积分
                $curpoint = $member['pay_points']+$change_point;         //当前的积分
                Db::name('user_wallet_log')->where('order_sn',$notifyInfo['out_trade_no'])->update(['pay_code'=>$notifyInfo['transaction_id'],'pay_status'=>1,'pay_time'=>time()]);     //更新支付记录
                Db::name('user')->where('uid',$order['uid'])->setInc('user_money',$order['amount']);        //更新会员余额
                Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$order['order_sn'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>$order['pay_type'],'pay_sign'=>2,'amount'=>$order['amount'],'addtime'=>time()]); //新增支付记录
                //更新积分
                if(ceil($order['amount']/10)>0){
                    Db::name('user_point_log')->insert(['uid'=>$order['uid'],'admin_id'=>0,'store_id'=>0,'order_id'=>0,'type'=>1,'point'=>$change_point,'curpoint'=>$curpoint,'remark'=>'充值赠送积分','addtime'=>time()]);
                    Db::name('user')->where('uid',$order['uid'])->setInc('level_point',$change_point);
                    Db::name('user')->where('uid',$order['uid'])->setInc('pay_points',$change_point);
                }
            }
        }
    }

    /**
     * @Author lignyun
     * @Desc    会员充值 -- 扫码充值回调
     */
    public function notifyweixinpay_code(){
        $pay = & load_wechat('Pay');
        // 获取支付通知
        $notifyInfo = $pay->getNotify();
        $resu = (array)simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA);
//$notifyInfo = file_get_contents("php://input");
        file_put_contents('log.txt',json_encode($resu));
        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            // 接口失败的处理
            $this->error('支付失败',url('User/index'),1);
        }else{
            //支付通知数据获取成功
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                $order = Db::name('user_wallet_log')->where("order_sn",$notifyInfo['out_trade_no'])->find();
                $member = Db::name('user')->where('uid',$order['uid'])->find();
                $cur_amount = $order['amount']+$member['user_money'];
                $point_rule = Db::name('sys_point')->where('id',3)->find();         //查询积分规则
                $change_point = ceil($order['amount']/$point_rule['score']);        //变更的积分
                $curpoint = $member['pay_points']+$change_point;         //当前的积分
                Db::name('user_wallet_log')->where('order_sn',$notifyInfo['out_trade_no'])->update(['pay_code'=>$notifyInfo['transaction_id'],'pay_status'=>1,'pay_time'=>time()]);     //更新支付记录
                Db::name('user')->where('uid',$order['uid'])->setInc('user_money',$order['amount']);        //更新会员余额
                Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$order['order_sn'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>$order['pay_type'],'pay_sign'=>2,'amount'=>$order['amount'],'addtime'=>time()]); //新增支付记录
                //更新积分
                if(ceil($order['amount']/10)>0){
                    Db::name('user_point_log')->insert(['uid'=>$order['uid'],'admin_id'=>0,'store_id'=>0,'order_id'=>0,'type'=>1,'point'=>$change_point,'curpoint'=>$curpoint,'remark'=>'充值赠送积分','addtime'=>time()]);
                    Db::name('user')->where('uid',$order['uid'])->setInc('level_point',$change_point);
                    Db::name('user')->where('uid',$order['uid'])->setInc('pay_points',$curpoint);
                }
            }
        }
    }

    /**
     * @Author lignyun
     * @Desc    支付宝支付回调业务处理  --  下单回调业务处理
     */
    public function notifyalipay(){
        $request = input('param.');     //回调参数
        $request = json_decode(json_encode($request),true);     //解码
//        $request = '{"gmt_create":"2017-12-27 18:36:09","charset":"UTF-8","gmt_payment":"2017-12-27 18:36:15","notify_time":"2017-12-28 04:00:27","subject":"\u8ba2\u5355\u652f\u4ed8","sign":"bYV5QzJj76sMdMQJeJyY3p\/6cmPoZGkGMvyHSM010TPT4RNkoYI+onJNWfAKCJiDcITqGVm+ZYVKKa+0uogOfc3j5oo8XKKaLKLhHFi8pTYFarFZsWdZwq+DR+lpPBMayCC4pCmYyKFrJ3S4GqgFko\/MleOq2\/m28bSdm2AXNij+Cx5dEJ9nMQodCIrEqJUNgbQe9mGoE54CrXRd4xc+aQ1WQk02XHWWYE13BWIBuZtrQLRSyBdK5eatzPBs3BlI5yEEAnhqvoG01PxmY4NWgHjaUZWEwdWZ9ANUwn+KW1KQ7o2rou3uUiKr+TZzHFgK3m4dr74CpObsmuLOrqwJiQ==","buyer_id":"2088902557566724","invoice_amount":"0.01","version":"1.0","notify_id":"804d756db7b0244cc037d63ff75201elk2","fund_bill_list":"[{&quot;amount&quot;:&quot;0.01&quot;,&quot;fundChannel&quot;:&quot;ALIPAYACCOUNT&quot;}]","notify_type":"trade_status_sync","out_trade_no":"201712271514370960963561","total_amount":"0.01","trade_status":"TRADE_SUCCESS","trade_no":"2017122721001004720205067586","auth_app_id":"2017112500161947","receipt_amount":"0.01","point_amount":"0.00","app_id":"2017112500161947","buyer_pay_amount":"0.01","sign_type":"RSA2","seller_id":"2088521346175024"}';
        $result = Query::exec($request['out_trade_no']);        //主动发起查询结果请求
        if($result['code'] == '10000'){     //调用接口成功
            if(isset($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS'){  //支付成功
                //查询订单信息
                $order = Db::name('order')->where('order_sn',$result['out_trade_no'])->find();
                //更新订单状态
                Db::name('order')->where('order_sn',$result['out_trade_no'])->update(['pay_code'=>$result['trade_no'],'pay_status'=>1,'pay_time'=>strtotime($result['send_pay_date']),'order_status'=>1,'remark'=>'已支付,'.$result['send_pay_date']]);
                //支付记录
                Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$result['out_trade_no'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>1,'pay_sign'=>1,'amount'=>$result['total_amount'],'addtime'=>time()]);
                //订单动作
                Db::name('order_action')->insert(['uid'=>$order['uid'],'order_id'=>$order['id'],'action_user'=>0,'order_status'=>1,'pay_status'=>1,'status_desc'=>'已支付，代发货','storeid'=>$order['store_id'],'addtime'=>time()]);
            }else{
                Db::name('order')->where('order_sn',$result['out_trade_no'])->update(['remark'=>$result['sub_msg']]);
            }
        }
    }

    /**
     * @Author lignyun
     * @Desc    会员充值 -- 支付宝回调
     */
    public function notifyalirecharge(){
        $request = input('param.');     //回调参数
        $request = json_decode(json_encode($request),true);     //解码
        $result = Query::exec($request['out_trade_no']);        //主动发起查询结果请求
        if($result['code'] == '10000'){     //调用接口成功
            if(isset($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS'){  //支付成功
                //查询订单信息
                $order = Db::name('user_wallet_log')->where('order_sn',$result['out_trade_no'])->find();
                //会员信息
                $member = Db::name('user')->where('uid',$order['uid'])->find();
                $cur_amount = $member['user_money']+$result['total_amount'];        //会员当前余额
                $point_rule = Db::name('sys_point')->where('id',3)->find();         //查询积分规则
                $change_point = ceil($result['total_amount']/$point_rule['point']);
                $curpoint = $member['pay_points']+$change_point; //当前的积分
                $level_point = $member['level_point']+$change_point;        //当前的会员等级积分
                //更新订单状态
                Db::name('user_wallet_log')->where('order_sn',$result['put_trade_no'])->update(['pay_code'=>$result['trade_no'],'pay_time'=>strtotime($result['send_pay_date']),'pay_status'=>1,'pay_type'=>1,'amount'=>$result['total_amount'],'cur_amount'=>$cur_amount,'sign'=>2,'chargetype'=>2,'charge_cn'=>'余额充值']);
                //记录支付日志
                Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$result['out_trade_no'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>1,'pay_sign'=>2,'amount'=>$result['total_amount'],'addtime'=>time()]);
                //变更会员余额
                Db::name('user')->where('uid',$order['uid'])->setInc('user_money',$result['total_amount']);
                //记录积分变更日志
                Db::name('user_point_log')->insert(['uid'=>$order['uid'],'store_id'=>0,'order_id'=>0,'uidtype'=>1,'signid'=>3,'type'=>1,'point'=>$change_point,'curpoint'=>$curpoint,'remark'=>'充值赠送积分','addtime'=>time()]);
                //更新会员等级积分
                Db::name('user')->where('uid',$order['uid'])->setInc('level_point',$change_point);
                Db::name('user')->where('uid',$order['uid'])->setInc('pay_points',$change_point);
                $rule = Db::name('sys_level')->order('score asc')->select();        //积分规则
                $level = userLevel($rule,$level_point);         //查看会员当前的等级
                Db::name('user')->where('id',$order['uid'])->update(['level_id'=>$level]);      //更新会员的等级规则id
            }else{
                Db::name('order')->where('order_sn',$result['out_trade_no'])->update(['remark'=>$result['sub_msg']]);
            }
        }
    }

//    public function noty(){
//        $json = file_get_contents("1.json");
//        $json = json_decode($json,true);
//        // Db::table("ys_notify")	->insert($json);
//        //dd($json);die;
//        // $noty = Db::table("ys_order")->where("order_sn",$json["out_trade_no"])->find();
//        $data = ["order_status"=>1,			"pay_type"=>2,	"pay_status"=>1,
//            "pay_name"=>"微信支付", 	"pay_time"=>time(),
//            "final_amount"=>$json["cash_fee"],		"transaction_id"=>$json["transaction_id"],
//            "pay_code"=>$json["transaction_id"]
//        ];
//        Db::table("ys_order")->where("order_sn",$json["out_trade_no"])->update($data);
//
//    }


}